﻿$(document).ready(function() {
    ShowMessages();
    Initialize();
});

function Initialize() {
    $("#buttonWriteNewMessage").bind("click", ShowMewMessageBody);
    $(".message-body").bind("click", ShowMessageBody);
    $("#buttonCancel").bind("click", CancelSending);
    $("#buttonSend").bind("click", SendMessage);
}

function CancelSending() {
    ShowMessagesTable();
    return false;
}
function Reply() {
    $("#MessageRecipient")[0].value = $("#SenderName")[0].value;
    ShowMewMessageBody();

}

function ShowMessages(requestedMessages) {
    var URL = document.location + "/GetRecievedMessages";
    $.getJSON(URL, RenderMessages);
}

function RenderMessages(messages) {
    $("#messages").setTemplate($("#MessageTemplate").html());
    $("#messages").processTemplate(messages);
    ShowMessagesTable();
    addHandlerForDelete();
}

function ShowMessageBody() {
    var url = document.location + "/" + $(this).attr('id');
    $.getJSON(url, RenderMessage);
}

function RenderMessage(message) {

}

function CutMessageBody(messageBody) {
    if (messageBody.toString().length < 66)
        return messageBody;
    return messageBody.toString().substring(0, 66) + "...";
}

function DeleteMessage(e) {
    var URL = document.location + "/DeleteMessage/" + parseFloat(e.currentTarget.id.replace("aDeleteMessage", ""));
    $.getJSON(URL, {}, onDeleteSucces);
    return;
}
function onDeleteSucces(data) {
    $("#StatusMessage")[0].innerHTML = data.message;
    ShowMessages();
}
function addHandlerForDelete() {
    $(".delete").bind("click", DeleteMessage);
    $(".reply").bind("click", Reply);
}
function CheckSenderId(id) {
    if (id)
        return id;
    return "";
}

function ShowMewMessageBody() {
    if ($("#divNewMessage").is(":hidden")) {
        $("#divNewMessage").slideToggle("normal");
        $("#messages").slideUp("normal");
    }
}

function ShowMessagesTable() {
    if ($("#messages").is(":hidden")) {
        $("#divNewMessage").slideUp("normal");
        $("#messages").slideToggle("normal");
    }
}

function SendMessage() {
    var message =
        {
            "Subject": $("#MessageSubject")[0].value,
            "MessageBody": $("#MessageBody")[0].value,
            "Recipient": $("#MessageRecipient")[0].value
        };
    var URL = document.location + "/SendMessage";

    $.post(URL, message, onSendSucess);
    return false;
}
function onSendSucess(data) {
    if (($("#StatusMessage")[0].innerHTML = data) == "Success") {
        ShowMessages();
    }
}